
//
//  MyDetailOrderViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/2/24.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//
//  订单详情
import UIKit
import MJRefresh
import Networking
import Alamofire
import PKHUD
import SwiftyJSON

class MyDetailOrderViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource, BottomShadow, AddCornerUIRectCorner, MyDetailOrderFootViewDelegte {
    
    let cellHeight: CGFloat = 164
    var orderDetailType: OrderDetailType = .waitPay
    var header: MyDetailOrderHeaderView?
    var footer: MyDetailOrderFootView?
    
    
    typealias deleteBlock = () -> ()
    var deleteblock: deleteBlock?
    var cancelblock: deleteBlock?
    var model: myOrderModel?{
        didSet{
            
            header?.model = model
            footer?.model = model
        }
    }
    
    var timeCount: TimeInterval?
    @IBOutlet weak var mainTableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        // Do any additional setup after loading the view.
    }
    
    func setUI() {
        self.view.backgroundColor = UIColor.lightGray
        mainTableView.register(UINib(nibName: "\(MyOrderTableViewCell.self)", bundle: nil), forCellReuseIdentifier: "\(MyOrderTableViewCell.self)")
        let headerView = MyDetailOrderHeaderView()
        headerView.showData(type: orderDetailType)
        headerView.model = model
        mainTableView.tableHeaderView = headerView
        header = headerView
        
        let footView = MyDetailOrderFootView()
        footView.showData(type: orderDetailType)
        footView.model = model
        footView.delegate = self
        footView.delegateVC = self
        mainTableView.tableFooterView = footView
        footer = footView
        self.fetchBannerList(parameters: ["id":(model?.id!)!])
    }

    override func setNavigation() {}
    
    //0:待付款；1：待发货；2：待收货；3：已完成；4：已取消；5：申请退换；6：同意退货；7：拒绝退货
    private func typeUI(type: OrderDetailType, typeLabel: UILabel, rightButton: UIButton) {
        var leftButtonIsHidden = true
        var rightButtonColor = UIColor(hex: 0x8F8F8F)
        var typeTitle = ""
        var typeTitleColor = ONColor.currencyRedColor
        switch type {
        case .waitPay:
            typeTitle = "待付款"
            rightButtonColor = ONColor.currencyRedColor
            rightButton.setTitle("立即付款", for: .normal)
        case .waitOut:
            typeTitle = "待发货"
            rightButtonColor = ONColor.currencyRedColor
            rightButton.setTitle("催单", for: .normal)
        case .out:
            typeTitle = "待收货"
            rightButtonColor = ONColor.currencyRedColor
            leftButtonIsHidden = false
            rightButton.setTitle("确认收货", for: .normal)
        case .done:
            typeTitle = "已完成"
            typeTitleColor = ONColor.normalTextColor
            rightButtonColor = ONColor.currencyRedColor
            rightButton.setTitle("再次购买", for: .normal)
        case .cancel:
            typeTitle = "已取消"
            rightButtonColor = ONColor.currencyRedColor
            rightButton.setTitle("立即付款", for: .normal)
        case .req:
            typeTitle = "申请退换"
            leftButtonIsHidden = false
            rightButtonColor = ONColor.currencyRedColor
            rightButton.setTitle("进行评价", for: .normal)
        case .agree:
            typeTitle = "同意退货"
            typeTitleColor = ONColor.normalTextColor
            rightButton.setTitle("再次购买", for: .normal)
        case .none:
            typeTitle = "拒绝退货"
            typeTitleColor = ONColor.normalTextColor
            rightButton.setTitle("再次购买", for: .normal)
        }
        
        typeLabel.textColor = typeTitleColor
        typeLabel.text = typeTitle
        //        leftButton.isHidden = leftButtonIsHidden
        rightButton.layer.borderColor = rightButtonColor.cgColor
        rightButton.setTitleColor(rightButtonColor, for: .normal)
    }
    
    // MARK: tableViewDatasource
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    // MARK: - tableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if let count = model?.purchaseGoodsInfos?.count{
            return count
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 35
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 35))
        let lable: UILabel = UILabel(frame: .zero)
        lable.font = UIFont.systemFont(ofSize: 12)
        lable.textColor = UIColor.black
        lable.text = "订单编号：" + (self.model?.orderNumber)!
        lable.left = 15
        lable.sizeToFit()
        lable.centerY = view.centerY;
        view.addSubview(lable)
        
        let button: UILabel = UILabel(frame: .zero)
        button.font = UIFont.systemFont(ofSize: 12)
        button.textColor = UIColor.red
        if let type = OrderDetailType(rawValue: Int((model?.status)!)!) {
            typeUI(type: type, typeLabel: button, rightButton: UIButton())
        }
        button.sizeToFit()
        button.right = view.right - 30
        button.centerY = view.centerY
//        view.addSubview(button)
        view.backgroundColor = UIColor.white
        //        addCornerWithView(aView: view, aCorners: [.bottomLeft, .bottomRight, .topLeft, .topRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        
        
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "\(MyOrderTableViewCell.self)") as? MyOrderTableViewCell
        cell?.x = 10
        cell?.width = ScreenWidth - 20
        cell?.backgroundColor = UIColor.clear
        cell?.contentView.x = 10
        cell?.contentView.width = ScreenWidth - 20
        if let type = OrderDetailType(rawValue: indexPath.row) {
            cell?.setData(type: type)
        }
        //        addCornerWithView(aView: (cell?.contentView)!, aCorners: [.bottomLeft, .bottomRight, .topLeft, .topRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        
        let model1 = model?.purchaseGoodsInfos![indexPath.row]
        cell?.bindData(data: model1!)
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 85
    }
  
    
    // MARK: - MyDetailOrderFootViewDelegte
    func paymentButtonTap(mode: myOrderModel) {
        if mode.status == "0" {
            let payVC = PayViewController(nibName: "PayViewController", bundle: nil)
            payVC.titleLabel(text: "选择支付方式", nil)
            payVC.orderId = mode.orderNumber
            self.navigationController?.pushViewController(payVC, animated: true)
            return
        }else if (mode.status == "4"){
            let buyNowVC = BuyNowViewController(nibName: "\(BuyNowViewController.self)", bundle: nil)
            buyNowVC.orderNumber = mode.orderNumber
            buyNowVC.type = 3
            self.navigationController?.pushViewController(buyNowVC, animated: true)
            return
        }
        CustomShowAlertView().show(title: "请确定已收到装备") { (done) in
            if done {
                self.navigationController?.popViewController(animated: true)
            }
        }
    
    }
    
    
    /// 获取banner数据
    func fetchBannerList(parameters: [String: String]) -> Void {
        let requesturl = "\(BaseURL)\(myOrderUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                    
                                        let subject = json["data"]
                                        
                                        let dic = subject.dictionary!
                                        var model = myOrderModel(fromDic: dic)
                                        model.initLabels(arr: (dic["purchaseGoodsInfos"]?.array!)!)
                                        if model.status == "0" {
                                            let payTime:Date = string2Date(dateString: model.lastPayTime!)
                                            let time = time2Time(date: payTime, another: Date())
                                            if time > 0{
                                                self.cancelOrder(paramaters: ["id": model.id!, "reason": "超时"])
                                                return;
                                            }else{
                                                self.timeCount = -time
                                                self.header?.timeCount = self.timeCount!
                                            }
                                        }
                                        self.model = model
                                        self.title = model.statusName
                                        
                                        self.mainTableView.reloadData()
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                       
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                              
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        
    }
    
    func cancelOrder(paramaters: [String: String]) -> Void {
        let requesturl = appendUrl(suffix: cancelOrderUrl)
        Alamofire.request(requesturl, method: .post,
                          parameters: paramaters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.cancelblock!()
                                       self.showToast(msg:json["message"].string!)
                                       self.navigationController?.popViewController(animated: true)
                                        
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                
                               self.showToast(msg:"网络错误")
                            }
                            
        }
    }
    
    
    func deleteOrder(paramaters: [String: String]) -> Void {
        let requesturl = appendUrl(suffix: deleteOrderUrl)
        Alamofire.request(requesturl, method: .get,
                          parameters: paramaters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.deleteblock!()
                                        self.showToast(msg:json["message"].string!)
                                        self.navigationController?.popViewController(animated: true)
                                        
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                
                                self.showToast(msg:"网络错误")
                            }
                            
        }
    }
    
    // MARK: - 售后点击
    func evaluateButtonTap(mode: myOrderModel) {
   
        
    }
    
    func customerServiceTap(mode: myOrderModel) {
      
        if model?.status == "4" {
            deleteOrder(paramaters: ["id": mode.id!])
            return;
        }else{
            cancelOrder(paramaters: ["id": mode.id!, "reason": "超时"])
            return
        }
        let afterSaleServiceVC = AfterSaleServiceViewController(nibName: "\(AfterSaleServiceViewController.self)", bundle: nil)
        navigationController?.pushViewController(afterSaleServiceVC, animated: true)
    }
}

